<?php

namespace app\admin\controller\lal;

use app\common\controller\Backend;
use think\Db;
use fast\Random;
use think\Config;

/**
 * 拉卡拉提现管理
 *
 * @icon fa fa-circle-o
 */
class Withdraw extends Backend
{

    /**
     * Withdraw模型对象
     * @var \app\admin\model\lal\Withdraw
     */
    protected $model = null;
    protected $store_shop_model = null;
    protected $service_model = null;
    protected $lal_member_model = null;
    protected $lal_member_info_model = null;
    protected $order_model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\lal\Withdraw;
        $this->store_shop_model = new \app\admin\model\store\Shop;
        $this->service_model = new \app\admin\model\service\Service;
        $this->lal_member_model = new \app\admin\model\lal\Member;
        $this->lal_member_info_model = new \app\admin\model\lal\MemberInfo;
        $this->order_model = new \app\admin\model\order\Order;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("cateList", $this->model->getCateList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            if ($params['amount'] < 0 || $params['amount'] == 0) {
                Db::rollback();
                $this->error(__('请填写正确的提现金额'));
            }

            if ($params['type'] == 0) {
                $shop_info = $this->store_shop_model->find($params['shop_id']);
                $params['name'] = empty($shop_info)?'':$shop_info['shopname'];
            }else{
                $shop_info = $this->service_model->find($params['shop_id']);
                $params['name'] = empty($shop_info)?'':$shop_info['name'];
            }
            $params['code'] = Random::numeric(30);
            $lal_member = $this->lal_member_model->where(['type'=>$params['type'],'shop_id'=>$params['shop_id'],'status'=>'1'])->find();
            if (empty($lal_member)) {
                Db::rollback();
                $this->error(__('请正确设置提现账户'));
            }

            $lal_member_info = $this->lal_member_info_model->where(['id'=>$lal_member['id']])->find();
            if (empty($lal_member_info)) {
                Db::rollback();
                $this->error(__('Operation failed'));
            }

            $lal_bank_info = Db::name('lal_bank')->where(['member_no'=>$lal_member['member_no'],'is_settle_card'=>1])->find();
            if (empty($lal_member_info)) {
                Db::rollback();
                $this->error(__('Operation failed'));
            }

            $params['menber_id'] = $lal_member['id'];
            $params['card'] = $lal_bank_info['card_no']; 
            $params['createtime'] = time();

            $amount = $params['amount'] * 100;

            $req_url = cdnurl('/api/member/split',true);

            $req_params                   = [
                'member_no'             => Config::get('lal_config.member_no'),         // 卖家标识
                'account_type'          => '1000',                                      // 账户类型编码
                'out_order_no'          => $params['code'],                             // 订单号
                'amount'                => $amount,                                     // 订单金额（单位：分）
            ];

            ///// 分账规则
            $req_params['split_rule_data']= ['split_list' => [
                ['member_no' => $lal_member_info['member_no'], 'amount' => $amount],
            ]];

            $res = send_request($req_url, json_encode($req_params),'POST');

            $params['status'] = 0;

            if (!$res || empty($res) || $res['code'] != 1) {
                $params['status'] = 1;
            }

            $result = $this->model->allowField(true)->save($params);

            if ($result === false) {
                Db::rollback();
                $this->error(__('No rows were inserted'));
            }

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    function getdetail(){
        $type = trim($this->request->post('type'));
        $shop_id = trim($this->request->post('shop_id'));

        if (empty($shop_id)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        //充值卡金额
        $where = [];
        $where['o.shop_id'] = $shop_id;
        $where['o.state'] = '6';
        $where['o.data_type'] = 'cards';
        $where['i.type'] = '4';
        $where['t.pay_way_id'] = ['in',['10','12']];
        $recharge_fee = Db::name('lal_member_entry')->alias('l')
            ->join('wanlshop_order o','o.id=l.order_id','left')
            ->join('wanlshop_order_item i','i.order_id=o.id','left')
            ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
            ->where($where)
            ->sum('l.bbalance');
            
        //卡项除充值卡以外的卡项金额
        $where['i.type'] = ['<>','4'];
        $cards_fee = Db::name('lal_member_entry')->alias('l')
                    ->join('wanlshop_order o','o.id=l.order_id','left')
                    ->join('wanlshop_order_item i','i.order_id=o.id','left')
                    ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                    ->where($where)
                    ->sum('l.bbalance');

        //购买商品/服务的总金额
        $where['o.data_type'] = 'goods';
        unset($where['i.type']);
        $goods_fee = Db::name('lal_member_entry')->alias('l')
                    ->join('wanlshop_order o','o.id=l.order_id','left')
                    ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                    ->where($where)
                    ->sum('l.bbalance');

        $purchase_fee = 0;
        if ($shop_id == 1) {
            //订货订单总金额               
            $where['o.data_type'] = 'merchant';
            $where['o.state'] = ['in',['3','4','6']];
            $purchase_fee = Db::name('lal_member_entry')->alias('l')
                            ->join('wanlshop_order o','o.id=l.order_id','left')
                            ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                            ->where($where)
                            ->sum('l.bbalance');
        }
        
        $total_amount = sprintf("%.2f",$cards_fee + $goods_fee + $purchase_fee);


        //储值余额提现金额
        $condi = [];
        $condi['shop_id'] = $shop_id;
        $condi['status'] = 0;
        $condi['cate'] = '0';
        $stored_withdraw_total = $this->model->where($condi)->sum('amount');

        //账户余额提现金额
        $condi['cate'] = '1';
        $account_withdraw_total = $this->model->where($condi)->sum('amount');


        $available_stored_withdraw = sprintf("%.2f", $recharge_fee - $stored_withdraw_total > 0?$recharge_fee - $stored_withdraw_total:0);

        $available_account_withdraw = sprintf("%.2f", $total_amount - $account_withdraw_total > 0?$total_amount - $account_withdraw_total:0);


        //当前已提现金额
        $condi = [];
        $condi['shop_id'] = $shop_id;
        $condi['status'] = 0;
        $withdraw_total = $this->model->where($condi)->sum('amount');

        $this->success('数据获取成功', '', ['valuebalance' => $recharge_fee,'accountbalance' => $total_amount,'withdraw_total'=>$withdraw_total,'storedwithdrawtotal' => $stored_withdraw_total,'accountwithdrawtotal' => $account_withdraw_total,'availablestoredwithdraw' => $available_stored_withdraw,'availableaccountwithdraw' => $available_account_withdraw,]);
    }

}
